import { find, Game, game as gameCCD} from 'cc';
import { _decorator, Component, Node, Label, tween, view, UITransform, Vec3, SpriteAtlas, SpriteFrame, Sprite, UIOpacity, EventTouch, Toggle, Prefab, instantiate } from 'cc';
import { App } from '../../App';
import { EventConst, localKey } from '../../common/Common';
import CommConst from '../../const/CommConst';
import wsTool from '../../net/ws';
import { LoadMg } from '../../tools/LoadMg';
import { showLuckyBallBet, showLuckyBallLottery, showLuckyBallRecord, showLuckyBallRule, showLuckyBallTrend, showTip } from '../../tools/PopuUp';
import { TipMg } from '../../tools/TipMg';
import UtilTool from '../../tools/UtilTool';
import { LBBallItemPanel } from './LBBallItemPanel';
import { LBBetPanel } from './LBBetPanel';
import { LBLotteryPanel } from './LBLotteryPanel';
import { LBRecordPanel } from './LBRecordPanel';
import { LBTrendPanel } from './LBTrendPanel';
const { ccclass, property } = _decorator;

// 幸运球主界面
@ccclass('LBMainPanel')
export class LBMainPanel extends Component {
    @property(Node)
    contentNode: Node = null;

    @property(Node)
    middleNode: Node = null;

    @property(Node)
    viewNode: Node = null;

    @property(Prefab)
    ballPrefab : Prefab

    @property(SpriteFrame)
    ballArr = []

    // 是否退到后台
    private isBackGround = false    

    // 游戏状态数据
    public gameData = {
        status: 0,      // 当前游戏状态 0下单中 1倒计时 2击球中
        countdown: 0,   // 倒计时：秒
        period: "0",    // 期数
        nums: "0",      // 本期数字（只有在击球阶段才会有）
        baseOdds: 0,    // 基础赔率
        hitOdds: 0,     // 击中赔率
        isReconnect: 0, // 是否重连 0否 1是
        list: [],       // 订单列表 list[{id=0, nums=0, value=0}]
    }

    // 游戏状态变化数据
    public gameStatusData = {
        status: 0,      // 当前游戏状态 0下单中 1倒计时 2击球中
        countdown: 0,   // 倒计时：秒
        period: "0",    // 期数
        nums: "0",      // 本期数字（只有在击球阶段才会有）
        hashId: "",     // 开奖hash
        blockHash: "",  // 开奖块hash
    }

    // 游戏状态
    private GAMESTATUS = {
        STATUS_ING : 0, // 下单中
        STATUS_DJS : 1, // 倒计时
        STATUS_HIT : 2, // 击球中
    }

    onLoad() {
        UtilTool.setScreen(this.node)
        this.node.getComponent(UITransform).setContentSize(view.getVisibleSize())

        gameCCD.on(Game.EVENT_HIDE, function(){
            if (this.node==null) return
            if(!this.isBackGround){
                this.isBackGround = true;
                UtilTool.printLog("切换后台");
                
            }
        }.bind(this));
        gameCCD.on(Game.EVENT_SHOW, function(){
            if (this.node==null) return
            if(this.isBackGround){
                UtilTool.printLog("切换前台");    
                this.isBackGround = false;
                this.reqGameData()
            }
        }.bind(this));

        App.Event.on(EventConst.UPDATE_MODE1_STATUS_CHANGE,this.updataStatus, this )
    }

    start() {
        App.WSGameStatus = 1
        LoadMg.removeLoad()
        this.createBall()

        this.reqGameData()
    }

    /** 
     * 创建球体
      */
    createBall() {
        let startX = -400
        let startY = 400
        let disX = 270
        let disY = 270
        this.middleNode.removeAllChildren()
        for (let i = 0; i < 16; i++) {
            let ballNodde = instantiate(this.ballPrefab)
            this.middleNode.addChild(ballNodde)

            let posx = startX + i%4 * disX
            let posy = startY - Math.floor(i/4) * disY
            ballNodde.setPosition(posx,posy)

            let isBet = false
            ballNodde.getComponent(LBBallItemPanel).setData({index:i, isBet:isBet},this)
        }
    }

    /**
     * 请求游戏数据
     */
    reqGameData(noLoad=false) {
        let that = this
        wsTool.send({"msgCode":CommConst.Req_ENTERGAME,"noLoad":noLoad})
        .then(res =>{
            // if (res?.result == 0) {
                UtilTool.printLog("游戏数据:",res)
                that.setGameConfig(res)
                that.uptateGameView(res)
                App.Event.emit(EventConst.UPDATE_MODE1_BALL,res.list, res.status, res.nums)
            // }
            // else{d
            //     alert('获取数据失败')
            // }
        })
    }

    /**
     * 设置游戏数据
     */
    setGameConfig(data) {
        if (data==null) return

        this.gameData.status = data.status
        this.gameData.countdown = data.countdown
        this.gameData.period = data.period
        this.gameData.nums = data.nums
        this.gameData.baseOdds = data.baseOdds
        this.gameData.hitOdds = data.hitOdds
        this.gameData.isReconnect = data.isReconnect
        this.gameData.list = data.list

        this.gameStatusData.status = data.status
    }

    /**
     * 设置游戏状态变化数据
     */
    setGameStatusConfig(data) {
        if (data==null) return

        this.gameStatusData.status = data.status
        this.gameStatusData.countdown = data.countdown
        this.gameStatusData.period = data.period
        this.gameStatusData.nums = data.nums
        this.gameStatusData.hashId = data.hashId
        this.gameStatusData.blockHash = data.blockHash

        this.gameData.status = data.status
    }

    /**
     * 更新游戏状态发送变化
     */
    updataStatus(data) {
        this.removeBetPanel()
        this.removeLotteryPanel()
        this.setGameStatusConfig(data)

        // 期数
        let periodLabel = find("timebg/periodLabel",this.contentNode).getComponent(Label)
        let newstr = App.language.getLanguageLab(14).replace("&", this.gameStatusData.period)
        periodLabel.string = newstr

        // 下注倒计时
        let timeLabel = find("timebg/timeLabel",this.contentNode).getComponent(Label)
        let nextLabel = find("timebg/nextLabel",this.contentNode).getComponent(Label)
        periodLabel.node.scale = new Vec3(0,0,0)
        nextLabel.node.scale = new Vec3(0,0,0)

        if (this.gameStatusData.status==this.GAMESTATUS.STATUS_ING) {
            // 进行中
            periodLabel.node.scale = new Vec3(1,1,1)
            UtilTool.timeCountdown(timeLabel, null, this.gameStatusData.countdown, null)
            this.gameData.list = []
            App.Event.emit(EventConst.UPDATE_MODE1_BALL,this.gameData.list, this.gameStatusData.status, this.gameStatusData.nums)
        }
        else if (this.gameStatusData.status==this.GAMESTATUS.STATUS_DJS) {
            // 开奖倒计时
            periodLabel.node.scale = new Vec3(1,1,1)
            this.showLotteryPanel(this.gameStatusData)
            UtilTool.timeCountdown(timeLabel, null, 0, null)
        }
        else if (this.gameStatusData.status==this.GAMESTATUS.STATUS_HIT) {
            // 击球中
            nextLabel.node.scale = new Vec3(1,1,1)
            this.showLotteryPanel(this.gameStatusData)
            UtilTool.timeCountdown(timeLabel, null, this.gameStatusData.countdown, null)
            App.Event.emit(EventConst.UPDATE_MODE1_BALL,this.gameData.list, this.gameStatusData.status, this.gameStatusData.nums)
        }
    }

    /**
     * 更新游戏界面
     */
    uptateGameView(res) {
        this.removeBetPanel()
        this.removeLotteryPanel()

        // 期数
        let periodLabel = find("timebg/periodLabel",this.contentNode).getComponent(Label)
        let newstr = App.language.getLanguageLab(14).replace("&", this.gameData.period)
        periodLabel.string = newstr

        // 下注倒计时
        let timeLabel = find("timebg/timeLabel",this.contentNode).getComponent(Label)
        let nextLabel = find("timebg/nextLabel",this.contentNode).getComponent(Label)
        periodLabel.node.scale = new Vec3(0,0,0)
        nextLabel.node.scale = new Vec3(0,0,0)

        if (this.gameData.status==this.GAMESTATUS.STATUS_ING) {
            // 进行中
            periodLabel.node.scale = new Vec3(1,1,1)
            UtilTool.timeCountdown(timeLabel, null, this.gameData.countdown, null)
        }
        else if (this.gameData.status==this.GAMESTATUS.STATUS_DJS) {
            // 开奖倒计时
            periodLabel.node.scale = new Vec3(1,1,1)
            UtilTool.timeCountdown(timeLabel, null, 0, null)
            this.showLotteryPanel(this.gameData)
        }
        else if (this.gameData.status==this.GAMESTATUS.STATUS_HIT) {
            // 击球中
            nextLabel.node.scale = new Vec3(1,1,1)
            UtilTool.timeCountdown(timeLabel, null, this.gameData.countdown, null)
            this.showLotteryPanel(this.gameData)
        }
    }

    /** 
     * 判断是否中奖
      */
    isLottery(number) {
        let lottery = false
        for (let i = 0; i < this.gameData.list.length; i++) {
            const data = this.gameData.list[i]
            if (data.nums == number) {
                UtilTool.printLog("中奖了",number)
                lottery = true
                break
            }
        }

        return lottery
    }

    /** 
     * 判断中奖的情况下是否击打过球
      */
    isHited(number) {
        let hit = true
        for (let i = 0; i < this.gameData.list.length; i++) {
            const data = this.gameData.list[i]
            if (data.nums == number) {
                // 击球状态 0未击球 1已进洞 2未进洞
                if (data.hitStatus==0) {
                    hit = false
                }
                
                break
            }
        }

        return hit
    }

    /** 
     * 玩法说明
      */
    clickRule() {
        App.Audio.playOneShot("click")
        showLuckyBallRule(this.viewNode)
    }

    /** 
     * 点击走势
      */
    async clickTrend() {
        App.Audio.playOneShot("click")
        let node = await showLuckyBallTrend(this.viewNode)
        node.getComponent(LBTrendPanel).setData(this)
    }

    /** 
     * 关闭
      */
    clickClose() {
        App.Audio.playOneShot("click")

        // 请求退出下注界面
        wsTool.send({"msgCode":CommConst.Req_EXITBET})
        .then(res =>{
            if (res?.result == 0) {
                UtilTool.printLog("退出成功:",res)
                this.node.destroy();
            }
        })
        
    }

    /** 
     * 购买记录
      */
    async clickRecode() {
        App.Audio.playOneShot("click")

        if (this.gameData.list.length<=0) {
            showTip(App.language.getLanguageLab(163))
            return
        }

        let node = await showLuckyBallRecord(this.viewNode)
        node.getComponent(LBRecordPanel).setData(this)
        node.setSiblingIndex(1000)
        // this.enterGame()
    }

    /** 
     * 进入游戏
      */
    enterGame() {
        // 请求退出下注界面
        // wsTool.send({"msgCode":CommConst.Req_EXITBET})
        // .then(res =>{
        //     if (res?.result == 0) {
        //         UtilTool.printLog("退出成功:",res)

                LoadMg.showLoad({type:1})
                App.Scene.go("game1")
        //     }
        // })
    }

    /** 
     * 展示下注界面
     * @param number 即将下注的号码
      */
    async showBetPanel(number) {
        this.removeBetPanel()

        let node = await showLuckyBallBet(this.middleNode)
        node.getComponent(LBBetPanel).setData(this, number)
    }

    /** 
     * 删除下注界面
      */
    removeBetPanel() {
        if (this.middleNode.getChildByName("lb_bet")) {
            this.middleNode.removeChild(this.middleNode.getChildByName("lb_bet"))
        }
    }

    /** 
     * 展示开奖界面
     * @param data 游戏数据
      */
    async showLotteryPanel(data) {
        this.removeLotteryPanel()
        
        let node = await showLuckyBallLottery(this.middleNode)
        node.getComponent(LBLotteryPanel).showView(this, data)
    }

    /** 
     * 删除开奖界面
      */
    removeLotteryPanel() {
        if (this.middleNode.getChildByName("lb_lottery")) {
            this.middleNode.removeChild(this.middleNode.getChildByName("lb_lottery"))
        }
    }

    onDestroy() {
        App.WSGameStatus = 0
        App.Event.off(EventConst.UPDATE_MODE1_STATUS_CHANGE,this.updataStatus, this )
    }
} 

